package me.frank.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.frank.security.repository.UserRepository;
import me.frank.security.dto.CustomUserDetails;
import me.frank.security.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/12/10 15:11
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserRepository, User> implements UserService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("登录用户名："+ username);
        User user = userRepository.selectOne(new QueryWrapper<User>().eq("username", username));
        return new CustomUserDetails(user);

    }

    @Override
    public boolean createUser(User user) {
        log.info("用户注册：" +user.toString());
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);
        return retBool(userRepository.insert(user));
    }
}
